#include <iostream>
#include <ctime>
#include <thread>
#include <unistd.h>
#include "block_queue.hpp"

using namespace std;

void product(blockqueue<string> &bq)
{
    unique_lock<mutex> ul(bq.pmut);
    while (1)
    {
        //获取数据
        int n = rand() % 10000;
        cout << "获取数据:" << to_string(n) << endl;
        sleep(1);
        while (bq.size() >= bq.max_capcity)
        {
            // 不使用if，因为可能造成伪唤醒
            cout << "任务已满,等待" << endl;
            bq.pcon.wait(ul);
        }
        cout << "生成任务" << endl;
        string name = "task" + to_string(n);
        bq.push(name);
        bq.ccon.notify_all();
        sleep(1);
    }
}

void consume(blockqueue<string> &bq)
{
    unique_lock<mutex> ul(bq.cmut);
    while (1)
    {
        while (bq.empty())
        {
            cout << "没有任务，等待" << endl;
            bq.ccon.wait(ul);
        }
        //获取任务
        string name = bq.front();
        cout << "get " << name << endl;
        bq.pop();
        bq.pcon.notify_all();
        sleep(1);
        //处理任务
        cout << "处理数据中。。。" << endl; 
        sleep(1);
    }
}

int main()
{
    srand(time(nullptr));
    blockqueue<string> bq;
    thread p[10];
    for(auto& e:p)
    {
        e = thread(product, ref(bq));
    }
    thread c[5];
    for(auto& e:c)
    {
        e = thread(consume, ref(bq));
    }
    // thread p(product, std::ref(bq));
    // thread c(consume, std::ref(bq));
    //blockqueue<string>对象需要在多个线程之间共享，并且需要通过引用传递。使用std::ref可以确保这一点
    sleep(1);
    for(auto& e:p)
    {
        e.join();
    }
    for(auto& e:c)
    {
        e.join();
    }
    // p.join();
    // c.join();

    return 0;
} 